//
//  MainViewController.m
//  Growth
//
//  Created by 洪波 陈 on 5/18/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "MainViewController.h"

#import "TLTrendsViewController.h"
#import "TimelineViewController.h"
#import "ToolBoxViewController.h"
#import "FriendsViewController.h"

#import "familyViewController.h"
#import "RecordViewController.h"

#import "NavTitleView.h"

@interface MainViewController ()

@end

@implementation MainViewController

@synthesize contentView;

@synthesize contentViewController;

@synthesize trendsViewController;
@synthesize personalViewController;
@synthesize familyViewController;
@synthesize toolsViewController;

@synthesize friendsViewController;
@synthesize settingsViewController;
@synthesize recordViewController;

@synthesize photoLibraryButton;
@synthesize currentImagePickerController;

- (void)dealloc
{
    
    [photoLibraryButton release];
    [currentImagePickerController release];
    [defaultTintColor release];
    
    [contentView release];
    
    [contentViewController release];
    [trendsViewController release];
    [personalViewController release];
    [familyViewController release];
    [toolsViewController release];
    
    [settingsViewController release];
    [recordViewController release];
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self navigationBarInit];
    [self tabBarInit];

    defaultTintColor = nil;
    
    selectedTabBarbutton = personalButton;
    
    [self tabBarAction:selectedTabBarbutton];
    
    self.navigationController.delegate = self;
    
    
    //登陆
    
    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]) {
        
        [self loadLoginView];
        
    }

    
    
    // Do any additional setup after loading the view from its nib.

}

#pragma mark--
#pragma mark 登陆处理

- (void)loadLoginView{
    
    LoginViewController *loginViewController = [[LoginViewController alloc] init];
    loginViewController.delegate = self;
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginViewController];
    
    [self.navigationController presentModalViewController:nav animated:NO];  
    
    [nav release];
    [loginViewController release];
    
    
}


#pragma mark --
#pragma mark  login view delegate

- (void)reloadData{
    
    selectedTabBarbutton = personalButton;
    [self tabBarAction:selectedTabBarbutton];
    
    [selectTimelineViewController reLoadData];
    [personalViewController reloadConttentData];
    
    
}

- (void)setTimelineTitle{
    
    UILabel *label = (UILabel *)[self.navigationItem.titleView viewWithTag:111];
    label.text = selectTimelineViewController.babyName;
    
    
    UIFont *font = [UIFont systemFontOfSize:20];
    CGSize size = CGSizeMake(200,2000);
    CGSize labelsize = [selectTimelineViewController.babyName sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap]; 
    
    UIView *view = [self.navigationItem.titleView viewWithTag:120];
    
    [label setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, labelsize.width, labelsize.height)];
    
    
    
    [label setCenter:CGPointMake(view.center.x -labelsize.width, view.center.y)];
    
    
    UIButton *selectTimelineButton = (UIButton *)[self.navigationItem.titleView viewWithTag:119];
    
    [selectTimelineButton setFrame:CGRectMake(label.frame.origin.x+label.frame.size.width, 0, 40, 40)];
    
    
    
}


#pragma mark end


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    CLog(@"View Will Appear");
    
    [super viewWillAppear:animated];
    
    [contentViewController viewWillAppear:animated];
//    if (defaultTintColor) {
//        UISegmentedControl *segmentedControl = (UISegmentedControl *)self.navigationItem.rightBarButtonItem.customView;
//        
//        // Before we show this view make sure the segmentedControl matches the nav bar style
//        if (self.navigationController.navigationBar.barStyle == UIBarStyleBlackTranslucent || self.navigationController.navigationBar.barStyle == UIBarStyleBlackOpaque)
//            segmentedControl.tintColor = [UIColor darkGrayColor];
//        else
//            segmentedControl.tintColor = defaultTintColor;
//    }
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



#pragma mark -
#pragma mark UINavigateBar

- (void)tabBarInit
{
    [trendsButton setImage:[UIImage imageNamed:@"icon_newthing2_iphone"] forState:UIControlStateSelected];
    [personalButton setImage:[UIImage imageNamed:@"icon_me2_iphone"] forState:UIControlStateSelected];
    //[cameraButton setImage:[UIImage imageNamed:@"icon_newthing2_iphone"] forState:UIControlStateSelected];
    [familyButton setImage:[UIImage imageNamed:@"icon_family2_iphone"] forState:UIControlStateSelected];
    [toolsButton setImage:[UIImage imageNamed:@"icon_gongju2_iphone"] forState:UIControlStateSelected];
}
- (void)navigationBarInit
{
    
    //    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_head_iPhone"]];
    //    [self.navigationController.navigationBar insertSubview:imageView atIndex:0];
    //    CLog(@"subview count %d", [[self.navigationController.navigationBar subviews] count]);
    
    //定义右侧按钮
    UIButton *rightButton1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [rightButton1 setImage:[UIImage imageNamed:@"icon_write_iphone.png"] forState:UIControlStateNormal];
    [rightButton1 addTarget:self action:@selector(recordViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton1 setCenter:CGPointMake(30, 15)];
    
    UIButton *rightButton2 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [rightButton2 setImage:[UIImage imageNamed:@"icon_friend_iphone.png"] forState:UIControlStateNormal];
    [rightButton2 addTarget:self action:@selector(friendsViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton2 setCenter:CGPointMake(70, 15)];
    
    UIView *rightButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 90, 30)];
    [rightButtonView addSubview:rightButton1];
    [rightButtonView addSubview:rightButton2];
    
    [rightButtonView setBackgroundColor:[UIColor clearColor]];
    
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButtonView];
    [rightButtonView release];
//    [rightButton1 release];
//    [rightButton2 release];
    
    self.navigationItem.rightBarButtonItem = rightItem;
    [rightItem release]; 
    
    //定义左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [leftButton setImage:[UIImage imageNamed:@"icon_shezhi_iphone.png"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(settingsViewAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [leftButton release];
    self.navigationItem.leftBarButtonItem = leftItem;
    [leftItem release];

    
    //定义返回按钮
    UIBarButtonItem * backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: @"返回" style:UIBarButtonSystemItemDone target:self action: nil];   
    
    [[self navigationItem] setBackBarButtonItem:backBarButtonItem];  
    [backBarButtonItem release]; 
    
    //iOS 5.0 Top bar效果优化
    double sysVersion = [[[UIDevice currentDevice] systemVersion] doubleValue];
    if (sysVersion >= 5.0) {
        //[backBarButtonItem setTintColor:[UIColor blueColor]];
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bgtopbar_zhujiemian_iphone.png"] forBarMetrics:UIBarMetricsDefault];

    }
}
 
#pragma mark -
#pragma mark Action

- (void)recordViewAction:(id)sender
{
    
//    if (recordViewController != nil) {
//        [recordViewController release];
//    }
//    
//    recordViewController = [[RecordViewController alloc] init];
//    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:recordViewController];
//    
//    [self.navigationController presentModalViewController:navController animated:YES];
//    [navController release];
    
    RecordViewController *content = [[RecordViewController alloc] init];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:content];
    CLog(@"content retain count %d", [content retainCount]);
    [content release];
    [self.navigationController presentModalViewController:navController animated:YES];

    [navController release];

}

- (void)settingsViewAction:(id)sender
{

    UIViewController *content = [[SettingViewController alloc] init];
    
    [self.navigationController pushViewController:content animated:YES];
    [content release];
   
}

- (void)friendsViewAction:(id)sender
{
    
    if (friendsViewController == nil) {
        friendsViewController = [[FriendsViewController alloc] init];
    }
    
    FriendsViewController *content = [[FriendsViewController alloc] init];
    [self.navigationController pushViewController:content animated:YES];
    [content release];
    //[self.navigationController presentModalViewController:friendsViewController animated:YES];
}



#pragma mark -
#pragma mark 顶部内容切换部分 Begine
- (void)loadTopViewWith:(NSInteger)index
{
    switch (index) {
        case 1:
        {
            [self loadTrendsTopView];
            break;
        } 
        case 2:
        {
            [self loadPersonalTopView];
            break;
        }
        case 3:
        {

            break;
        }
        case 4:
        {
            [self loadFamilyTopView];
            break;
        }
        case 5:
        {
            [self loadToolsTopView];
            break;
        }
        default:
            break;
    }
}

//加加载动态顶部切换按钮
- (void)loadTrendsTopView
{
    [selectedTabBarbutton setSelected:NO];
    
    selectedTabBarbutton = trendsButton;
    [selectedTabBarbutton setSelected:YES];

    
    NSArray *segmentTextContent = [NSArray arrayWithObjects:
                                   @"最新",
                                   @"最热",
								   nil];
	UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentTextContent];
	segmentedControl.selectedSegmentIndex = 0;
	segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleHeight;
	segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
	segmentedControl.frame = CGRectMake(0, 0, 100, kCustomButtonHeight);
	[segmentedControl addTarget:self action:@selector(trendsSegmentAction:) forControlEvents:UIControlEventValueChanged];
	
    //segmentedControl.tintColor = [UIColor greenColor];
    
	defaultTintColor = [segmentedControl.tintColor retain];	// keep track of this for later
    
	self.navigationItem.titleView = segmentedControl;
	[segmentedControl release];
}

- (IBAction)trendsSegmentAction:(id)sender
{
    
       
	// The segmented control was clicked, handle it here 
	UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
    NSInteger index = segmentedControl.selectedSegmentIndex;
	NSLog(@"Segment clicked: %d", index);
    
    if (trendsViewController != nil) {
        switch (index) {
            case 0:
            {
                [trendsViewController loadNews];
                
                break;
            }
            case 1:
            {
                [trendsViewController loadpopular];
                
                break;
            }
            default:
                break;
        }
    }
    
}

//加加载首页顶部切换按钮
- (void)loadPersonalTopView
{
    CLog(@"宝宝主页");
    
    [selectedTabBarbutton setSelected:NO];
    
    selectedTabBarbutton = personalButton;
    [selectedTabBarbutton setSelected:YES];

    
    if (selectTimelineViewController == nil) {
        
        selectTimelineViewController = [[SelectTimelineViewController alloc]init];
        selectTimelineViewController.delegate = self;
        [self.view addSubview:selectTimelineViewController.view];
        [selectTimelineViewController.tableView reloadData];
        selectTimelineViewController.view.hidden = YES;
    }

    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 220, 40)];
    view.tag = 120;
    view.backgroundColor = [UIColor clearColor];
    view.userInteractionEnabled = YES;
    UILabel *nameLabel = [[UILabel alloc]init];
    nameLabel.tag =111;
     
    nameLabel.backgroundColor = [UIColor clearColor];
    nameLabel.numberOfLines = 0;
    nameLabel.textColor = [UIColor whiteColor];
    [nameLabel setFont:[UIFont boldSystemFontOfSize:20]];
   
    
    [nameLabel setTextAlignment:UITextAlignmentCenter];
    
    [view addSubview:nameLabel];
  
           
    if (selectTimelineViewController.babyName) {
        
       nameLabel.text = selectTimelineViewController.babyName;
        
    }
    else{
        
       nameLabel.text = @"宝宝主页";
        
    }
       
    UIFont *font = [UIFont systemFontOfSize:20];
    CGSize size = CGSizeMake(200,2000);
    CGSize labelsize = [selectTimelineViewController.babyName sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap]; 
    
    
    [nameLabel setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, labelsize.width, labelsize.height)];

    
    [nameLabel setCenter:CGPointMake(view.center.x-labelsize.width/2, view.center.y)];
    
    
        UIButton *selectTimelineButton = [[UIButton alloc]initWithFrame:CGRectMake(nameLabel.frame.origin.x+nameLabel.frame.size.width, 0, 40, 40)]; 
    selectTimelineButton.tag = 119;
    
    [selectTimelineButton setImage:[UIImage imageNamed:@"bt_arrow_iphone.png"] forState:UIControlStateNormal];
    [selectTimelineButton addTarget:self action:@selector(addTimelineSelectView ) forControlEvents:UIControlEventTouchUpInside];
    //[self.navigationItem.titleView addSubview:selectTimelineButton];
    
    [view addSubview:selectTimelineButton];
    
      [selectTimelineButton release];
    
        self.navigationItem.titleView = view;
    self.navigationItem.titleView.userInteractionEnabled = YES;
  
    [nameLabel release];
    
    self.navigationController.title = @"";
    //self.navigationItem.titleView = nil;
    
        
}

//加载选时间轴列表

- (void)addTimelineSelectView{
    
    if (selectTimelineViewController == nil) {
        
        selectTimelineViewController = [[SelectTimelineViewController alloc]init];
         selectTimelineViewController.delegate = self;
        [self.view addSubview:selectTimelineViewController.view];
        [selectTimelineViewController.tableView reloadData];
    }
    if (selectTimelineViewController.view.hidden == YES) {
        
        int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
        
        [selectTimelineViewController loadTimelineMember:uid  ];
        selectTimelineViewController.view.hidden = NO;
    }
    else{
        
        selectTimelineViewController.view.hidden = YES;
    }
    
}

//加加载动态顶部切换按钮
- (void)loadFamilyTopView
{
    [selectedTabBarbutton setSelected:NO];
    
    selectedTabBarbutton = familyButton;
    [selectedTabBarbutton setSelected:YES];

    
    self.navigationItem.title = @"家人";
    self.navigationItem.titleView = nil;
}

//加加载动态顶部切换按钮
- (void)loadToolsTopView
{
    [selectedTabBarbutton setSelected:NO];
    
    selectedTabBarbutton = toolsButton;
    [selectedTabBarbutton setSelected:YES];

    UIView *titleView = [[NavTitleView alloc] initWithTitle:@"工具"];
    self.navigationItem.titleView = titleView;
    [titleView release];    

}

//加载相机
- (void)loadCameraView{
    
    [self showCamera:nil];
}

#pragma mark 顶部内容切换部分 End
#pragma mark -



#pragma mark -
#pragma mark UINavigationDelegate

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    
    //刷新主页
//    if (viewController == self) {
//        
//        if (contentViewController == personalViewController) {
//            
//            if ([[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] && [[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]) {
//                
//                int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
//                int tid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] intValue];
//                
//                personalViewController.pageNo = 1;
//                [personalViewController loadTimelineMember:uid];
//                [personalViewController loadTimelineData:uid timelineId:tid pageNo:personalViewController.pageNo pageSize:10];
//        
//                
//            }
//            
//
//            
//        }
//        
//               
//    }
   
        
    [self addSomeElements:viewController];

}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    
    
}


#pragma mark -
#pragma mark UINavigationBarDelegate
//- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPushItem:(UINavigationItem *)item
//{
//    CLog(@"shouldPushItem");
//    
//    return YES;
//}
//- (void)navigationBar:(UINavigationBar *)navigationBar didPushItem:(UINavigationItem *)item
//{
//    CLog(@"didPushItem");
//}
//- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
//{
//    CLog(@"shouldPopItem");
//    return YES;
//}
//- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item
//{
//    CLog(@"didPopItem");
//}
#pragma mark -
#pragma mark Tab Bar Action
- (IBAction)tabBarAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    NSInteger index = button.tag;
    
    [self loadContentViewWith:index];
    
    CLog(@"Choose %d", index);
    
    
}


#pragma mark UITabbarDelegate

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    NSInteger index = item.tag;
    
    [self loadContentViewWith:index];
    
    CLog(@"Choose %d", index);

}


- (void)loadContentViewWith:(NSInteger)index
{
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    
    
    UIViewController *content = nil;
    
    switch (index) {
        case 1:
        {
            if (trendsViewController == nil) {
                
                CLog(@"TLTrendsViewController reload!");
                trendsViewController = [[TLTrendsViewController alloc] init];
                trendsViewController.delegate = appDelegate.viewController;
                
            }
            content = trendsViewController;
            
            break;
        }
        case 2:
        {
            if (personalViewController == nil) {
                CLog(@"TimelineViewController reload!");
                personalViewController = [[TimelineViewController alloc] init];
                  personalViewController.delegate = appDelegate.viewController;
            }
            content = personalViewController;
            break;
        } 
        case 3:
        {
            CLog(@"Camera");
            content = nil;
                 
            [self showCamera:nil];

            return;
            break;
        } 
        case 4:
        {
            if (familyViewController == nil) {
                CLog(@"FamilyViewController reload!");
                familyViewController = [[FamilyViewController alloc] init];
                 
            }
            content = familyViewController;
            break;
        } 
        case 5:
        {
            if (toolsViewController != nil) {
                [toolsViewController release];
                toolsViewController = nil;
            }
            
            if (toolsViewController == nil) {
                CLog(@"ToolBoxViewController reload!");
                toolsViewController = [[ToolBoxViewController alloc] init];
            }
            content = toolsViewController;
            break;
        } 
        default:
            break;
    }
    
    CLog(@"content %@", content);
    
    if (content != nil) {
        if (content != contentViewController) {
            if (contentViewController != nil) {
                [contentViewController.view removeFromSuperview];
            }
            //如果上一个是Tool界面释放掉
            if (contentViewController == toolsViewController) {
                [toolsViewController release];
                toolsViewController = nil;
            }
            
            contentViewController = content;
            
            [contentView addSubview:contentViewController.view];
            
            
            double sysVersion = [[[UIDevice currentDevice] systemVersion] doubleValue];
            if (sysVersion < 5.0) {
                CLog(@"ios view will appear");
                [contentViewController viewWillAppear:NO];
            }
            
            
            [self loadTopViewWith:(NSInteger)index];
            
        } 
        
    }
}



#pragma mark 顶部切换时间轴delegate
-(void)addTimeline{
    
//    if (personalViewController != nil) {
//        [personalViewController addTimeline];
//    }
    
     
    TimelineSettingViewController *viewController = [[TimelineSettingViewController alloc]initWithTimelineDict:nil];
    
    [self.navigationController pushViewController:viewController animated:YES];
  
}

-(void)changeTimeline:(int)babyId{
    
    if (selectTimelineViewController != nil) {
        
        UILabel *label = (UILabel *)[self.navigationItem.titleView viewWithTag:111];
        label.text = selectTimelineViewController.babyName;
       
        
        UIFont *font = [UIFont systemFontOfSize:20];
        CGSize size = CGSizeMake(200,2000);
        CGSize labelsize = [selectTimelineViewController.babyName sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap]; 
        
          UIView *view = [self.navigationItem.titleView viewWithTag:120];
        
        [label setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, labelsize.width, labelsize.height)];
                
     
        
        [label setCenter:CGPointMake(view.center.x -labelsize.width, view.center.y)];
    
        
        UIButton *selectTimelineButton = (UIButton *)[self.navigationItem.titleView viewWithTag:119];
        
        [selectTimelineButton setFrame:CGRectMake(label.frame.origin.x+label.frame.size.width, 0, 40, 40)];
        

    }
    
        
    int tid ;
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"]) {
        tid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] intValue];
    }
    
    if (personalViewController != nil) {
      
        personalViewController.babyrow = babyId;
        [personalViewController changeTimeline:tid];
    }
}


#pragma mark 调相机
- (IBAction)showCamera:(id)sender
{
	
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
		
		UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
		imagePickerController.sourceType=UIImagePickerControllerSourceTypeCamera;
		imagePickerController.delegate = self;
		imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
		imagePickerController.allowsImageEditing = YES;
		
		if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
			if (photoLibraryButton == nil) {
				
				UIButton *button = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
				button.backgroundColor = [UIColor clearColor];
				button.frame = CGRectMake(320 -20 -10 -22, 454 -15, 44, 30);
                // [button setImage:[UIImage imageNamed:@"button_bt_iphone.png"] forState:UIControlStateNormal];
				
                [button setImage:[UIImage imageNamed:@"bt_album_iphone.png"] forState:UIControlStateNormal];
				
				[button addTarget:self action:@selector(showPhotoLibrary:) forControlEvents:UIControlEventTouchUpInside];
				photoLibraryButton = button;
			}
			
			[imagePickerController.view addSubview:photoLibraryButton];
		}
		
		currentImagePickerController = imagePickerController;
		[self.navigationController presentModalViewController:imagePickerController animated:YES];
		[imagePickerController release];
		
	}
	else if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
		UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
        //	imagePickerController.mediaTypes = [NSArray arrayWithObjects:(NSString*)kUTTypeImage,(NSString*)kUTTypeMovie,nil];
		imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
		imagePickerController.delegate = self;
		imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
		currentImagePickerController = imagePickerController;
		[self.navigationController presentModalViewController:imagePickerController animated:YES];
		[imagePickerController release];
	}
	else if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
		UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
        //imagePickerController.mediaTypes = [NSArray arrayWithObject:(NSString*)kUTTypeImage];
		imagePickerController.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
		imagePickerController.allowsEditing = YES;
		imagePickerController.delegate = self;
		imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
		currentImagePickerController = imagePickerController;
		[self.navigationController presentModalViewController:imagePickerController animated:YES];
		[imagePickerController release];
	}
	
	
}


- (IBAction)showPhotoLibrary:(id)sender
{
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
		if (currentImagePickerController) {
			[currentImagePickerController dismissModalViewControllerAnimated:NO];
		}
		[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(showPhotoLibrary) userInfo:nil repeats:NO];
	}
	
}

-(void)showPhotoLibrary
{
	UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
	//imagePickerController.mediaTypes = [NSArray arrayWithObjects:(NSString*)kUTTypeImage,(NSString*)kUTTypeMovie,nil];
	imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
	imagePickerController.delegate = self;
	imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
	currentImagePickerController = imagePickerController;
	[self.navigationController presentModalViewController:imagePickerController animated:YES];
	[imagePickerController release];
}

#pragma mark  Camera
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
	
   
    if (recordViewController != nil) {
        [recordViewController release];
    }
    
    recordViewController = [[RecordViewController alloc] initWithImage:image];

     [picker dismissModalViewControllerAnimated:NO];
    
    
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:recordViewController];
    
    [self.navigationController presentModalViewController:navController animated:YES];   
	//[self.navigationController pushViewController:recordViewController animated:YES];
	
	
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	
	if (picker == currentImagePickerController) {
		currentImagePickerController = nil;
	}
	
	[picker dismissModalViewControllerAnimated:YES];
	
	//[self.view setFrame:CGRectMake(0, 0, 320, 480)];
}


-(void)addSomeElements:(UIViewController *)viewController{
	//Add the motion view here, PLCameraView and picker.view are both OK
	UIView *PLCameraView=[self findView:viewController.view withName:@"PLCameraView"];
	
	//Get Bottom Bar
	UIView *bottomBar=[self findView:PLCameraView withName:@"PLCropOverlayBottomBar"];
	
	//Get ImageView For Save
	UIImageView *bottomBarImageForSave = [bottomBar.subviews objectAtIndex:0];
	
	//Get Button 0
	UIButton *retakeButton=[bottomBarImageForSave.subviews objectAtIndex:0];
	[retakeButton addTarget:self action:@selector(showLibraryButton) forControlEvents:UIControlEventTouchUpInside];
	
	//Get ImageView For Camera
	UIImageView *bottomBarImageForCamera = [bottomBar.subviews objectAtIndex:1];
	
	//Get Button 0(The Capture Button)
	UIButton *cameraButton1=[bottomBarImageForCamera.subviews objectAtIndex:0];
	[cameraButton1 addTarget:self action:@selector(hideLibraryButton) forControlEvents:UIControlEventTouchUpInside];
	
}
//Find the view we want in camera structure.
-(UIView *)findView:(UIView *)aView withName:(NSString *)name{
	Class cl = [aView class];
	NSString *desc = [cl description];
	
	if ([name isEqualToString:desc])
		return aView;
	
	for (NSUInteger i = 0; i < [aView.subviews count]; i++)
	{
		UIView *subView = [aView.subviews objectAtIndex:i];
		subView = [self findView:subView withName:name];
		if (subView)
			return subView;
	}
	return nil;	
}

- (void)hideLibraryButton
{
	self.photoLibraryButton.hidden = YES;
}
- (void)showLibraryButton
{
	[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(showLibraryButtonAfterDelay) userInfo:nil repeats:NO];
	
}

- (void)showLibraryButtonAfterDelay
{
	
	photoLibraryButton.hidden = NO;
}




@end
